package org.happy.tester.common.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.happy.tester.common.constant.CommonConstant.DEFAULT_USER_AGENT;

/**
 * Description
 *
 * @author baijingchuan
 * Date 2020/6/10
 **/
public class OkHttpClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpClientUtil.class);

    private OkHttpRequestProvider requestProvider;

    protected Map<String, String> paramMap;

    Response response = null;

    public String doSyncPostJson(JSONArray reqParam) {
        String jsonParam = reqParam.toJSONString();
        Request request = getRequestProvider().postJsonRequest(jsonParam);
        try {
            response = OkHttpClientProvider.SINGLETON_CLIENT.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOGGER.error("do sync post with json error 【{}】", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    public void doAsyncPostJson(JSONObject reqParam) {
        String jsonParam = reqParam.toJSONString();
        Request request = getRequestProvider().postJsonRequest(jsonParam);
        OkHttpClientProvider.SINGLETON_CLIENT.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                LOGGER.error("do async post with json error 【{}】", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                LOGGER.debug("do sync post with json success");
                response.close();
            }
        });
    }

    public String doSyncPostForm() {
        Request request = getRequestProvider().postFormRequest(paramMap);
        try {
            response  = OkHttpClientProvider.SINGLETON_CLIENT.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            LOGGER.error("do sync post with form error 【{}】", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    public void doAsyncPostForm() {
        Request request = getRequestProvider().postFormRequest(paramMap);
        OkHttpClientProvider.SINGLETON_CLIENT.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                LOGGER.error("do async post with json form 【{}】", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                LOGGER.debug("do async post with json success");
                response.close();
            }
        });
    }

    public String doSyncGet() {
        Request request = getRequestProvider().getRequest(paramMap);
        String result = "";
        try {
            response = OkHttpClientProvider.SINGLETON_CLIENT.getInstance().newCall(request).execute();
            result = response.body().string();
            if (response.isSuccessful()) {
                return result;
            }
        } catch (IOException e) {
            LOGGER.error("do sync get error【{}】", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    public void doAsyncGet() {
        Request request = getRequestProvider().getRequest(paramMap);
        OkHttpClient okHttpClient = OkHttpClientProvider.SINGLETON_CLIENT.getInstance();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                LOGGER.error("do async get error【{}】", e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                LOGGER.debug("do async get success【{}】");
                response.close();
            }
        });
    }

    protected void initOkHttpRequestProvider(String rootPath, String path, Map<String, String> headers) {
        this.paramMap = new HashMap<>();
        OkHttpRequestProvider requestProvider = new OkHttpRequestProvider();
        requestProvider.setRootPath(rootPath);
        requestProvider.setPath(path);
        headers.put("user-agent", DEFAULT_USER_AGENT);
        requestProvider.setHeaders(headers);
        setRequestProvider(requestProvider);
    }

    public OkHttpRequestProvider getRequestProvider() {
        return requestProvider == null ? new OkHttpRequestProvider() : requestProvider;
    }

    public void setRequestProvider(OkHttpRequestProvider requestProvider) {
        this.requestProvider = requestProvider;
    }

    public Map<String, String> getParamMap() {
        return paramMap;
    }

    public void setParamMap(Map<String, String> paramMap) {
        this.paramMap = paramMap;
    }

}
